﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using XenoGears.Logging;
using XenoGears.Reflection.Attributes;

namespace Prjinit.Templates.Core
{
    internal abstract class Template
    {
        protected LevelLogger Debug { get { return Log.Debug; } }
        protected LevelLogger Info { get { return Log.Info; } }
        protected LevelLogger Error { get { return Log.Error; } }

        private Logger _cachedLog;
        protected Logger Log
        {
            get
            {
                if (_cachedLog == null)
                {
                    _cachedLog = Logger.Get(GetType());
                    _cachedLog.MinLevel = Cfg.IsVerbose ? Level.Debug : Level.Info;
                }

                return _cachedLog;
            }
        }

        protected Config Cfg { get { return Config.Current; } }
        public abstract void Bootstrap();

        public static String Default
        {
            get
            {
                var asm = MethodInfo.GetCurrentMethod().DeclaringType.Assembly;
                var templates = asm.GetTypes().Where(t => t.HasAttr<TemplateAttribute>()).ToArray();
                var @default = templates.SingleOrDefault(t => t.HasAttr<DefaultAttribute>());
                return @default == null ? null : @default.Attr<TemplateAttribute>().Aliases.First();
            }
        }

        public static Template Resolve(String providerName)
        {
            var asm = MethodInfo.GetCurrentMethod().DeclaringType.Assembly;
            var templates = asm.GetTypes().Where(t => t.HasAttr<TemplateAttribute>()).ToArray();

            var map = new Dictionary<String, Type>();
            foreach (var template in templates)
            {
                foreach (var name in template.Attr<TemplateAttribute>().Aliases)
                {
                    map.Add(name.ToLower(), template);
                    map.Add("-" + name.ToLower(), template);
                }
            }

            Type t_provider;
            if (!map.TryGetValue(providerName.ToLower(), out t_provider)) return null;
            return (Template)Activator.CreateInstance(t_provider);
        }
    }
}